#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>


//#define DEBUG 1

#define NUM 1024
#define SIZE 64
#define SUB " "


//获取用户名/主机名/当前工作目录
char* getUser()
{
  char* ret = getenv("USER");
  return ret;
}

char* getHostName()
{
  char* ret = getenv("HOSTNAME");
  return ret;
}

char* getCwd()
{
  char* ret = getenv("PWD");
  return ret;
}


//获取用户输入
int getUserCommand(char* usercommand)
{
  printf("[%s@%s %s]", getUser(), getHostName(), getCwd());
  fgets(usercommand, NUM, stdin);
  usercommand[strlen(usercommand) - 1] = '\0';
  return strlen(usercommand);
#ifdef DEBUG
  printf("%s\n", usercommand);
#endif
}

//分割用户输入的字符串
void commandSplit(char* const usercommand, char* argv[])
{
  int argc = 0;
  argv[argc++] = strtok(usercommand, SUB);
  while(argv[argc++] = strtok(NULL, SUB));

#ifdef DEBUG
  for(int i = 0; argv[i]; i++)
  {
    printf("%d:%s\n", i, argv[i]);
  }
#endif
}

//执行命令
int excuCommand(char* const argv[])
{
  pid_t id = fork();
  if(id < 0) return -1;
  else if(id == 0)
  {
    const char* file = argv[0];
    execvp(file, argv);
    exit(1);
  }
  else
  {
    int status = 0;
    pid_t wid = waitpid(id, &status, 0);
    if(WIFEXITED(status))
#ifdef DEBUG
      printf("%d\n", WEXITSTATUS(status));
#endif
    return wid;
  }
}

//执行内建命令
void cd(const char* path)
{
  chdir(path);
}

int buildIn(char* const argv[])
{
  if(strcmp(argv[0], "cd") == 0)
  {
    const char* path = argv[1];
    if(path == NULL)
      path = ".";
    cd(path);
    return 1;
  }
  else if(0)
  {
    return 1;
  }
  else return 0;
}

int main()
{
  while(1)
  {
    char usercommand[NUM];
    char* argv[SIZE];
    //1.获取用户输入
    int len = getUserCommand(usercommand);
    if(len <= 0)
      continue;
    //2.截取字符串命令
    commandSplit(usercommand, argv);

    //3.判断是否是内建命令，如果是直接执行
    int build_check = buildIn(argv);
    if(build_check) continue;

    //4.执行用户命令
    int exitcode = excuCommand(argv);
  }
}














